//
//  SignUpViewController.m
//  ShangHaiTuJI
//
//  Created by xiaoxiangtuji on 2017/7/29.
//  Copyright © 2017年 xiaoxiangtuji. All rights reserved.
//

#import "SignUpViewController.h"
#import "CommitDataViewController.h"
#import "signDetailPictureCell.h"
#import "QQAndWechatShareView.h"
#import "UMSocialQQHandler.h"
#import "WXApi.h"
#import "AppDelegate.h"
#import "LoginUserViewController.h"
@interface SignUpViewController ()<UITableViewDataSource,UITableViewDelegate,UITabBarControllerDelegate,UITabBarDelegate>
{
    CGFloat _rowheight;
    AppDelegate *appdelegate;
    CGFloat _offsetY;

}

@property(nonatomic,strong)UIImageView *matchImageView;
@property(nonatomic,strong)UIButton *applyBtn;
@property(nonatomic,strong)UITableView *tableView;
@property(nonatomic,strong)NSMutableArray *imagesArray;
@property(nonatomic,strong)NSMutableArray *rowsArray;
@property(nonatomic,strong)QQAndWechatShareView *shareView;
@property(nonatomic,strong)UIView *showView;
@property (nonatomic,assign) NSInteger  indexFlag;

@end

@implementation SignUpViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"赛事详情";
    [self setShareBtn];
    [self createtableView];
    [self getMatchDetailInformation];
    // Do any additional setup after loading the view.
}
-(void)setShareBtn{
    if ([UIDevice currentDevice].userInterfaceIdiom == UIUserInterfaceIdiomPad) {
        if ([WXApi isWXAppInstalled]) {
            UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [shareBtn setBackgroundImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
            [shareBtn addTarget:self action:@selector(showShareUI) forControlEvents:UIControlEventTouchUpInside];
            shareBtn.frame = CGRectMake(WIDTH - 30, 6, 20, 20);
            UIBarButtonItem *flexSpac = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
            flexSpac.width = -10;
            UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:shareBtn];
            self.navigationItem.rightBarButtonItems = @[flexSpac,rightItem];
        }else{

        }
    }else{
        UIButton *shareBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [shareBtn setBackgroundImage:[UIImage imageNamed:@"share"] forState:UIControlStateNormal];
        [shareBtn addTarget:self action:@selector(showShareUI) forControlEvents:UIControlEventTouchUpInside];
        shareBtn.frame = CGRectMake(WIDTH - 30, 6, 20, 20);
        UIBarButtonItem *flexSpac = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil];
        flexSpac.width = -10;
        UIBarButtonItem *rightItem = [[UIBarButtonItem alloc] initWithCustomView:shareBtn];
        self.navigationItem.rightBarButtonItems = @[flexSpac,rightItem];
    }

}
-(void)createtableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 64, WIDTH, HEIGHT - 64) style:UITableViewStylePlain];
    [self.view addSubview:self.tableView];
    self.tableView.dataSource = self;
    self.tableView.delegate = self;
    [self.tableView registerClass:[signDetailPictureCell class] forCellReuseIdentifier:@"signDetailPictureCell"];
    self.tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.imagesArray.count ;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == self.imagesArray.count) {
        static NSString *cellId = @"cellID";
        UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellId];
        if (cell == nil) {
            cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellId];
        }
        [cell.contentView addSubview:self.showView];
        return cell;
    }else{
        signDetailPictureCell *pictrueCell = [tableView dequeueReusableCellWithIdentifier:@"signDetailPictureCell"];
        [pictrueCell.ImageView sd_setImageWithURL:[NSURL URLWithString:self.imagesArray[indexPath.row]] placeholderImage:[UIImage imageNamed:@""]];
        return pictrueCell;
    }

}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (indexPath.row == self.imagesArray.count) {
      return scaleTopAndBottom(70);
    }
    return [self.rowsArray[indexPath.row] floatValue];
}
-(void)getMatchDetailInformation{
    dispatch_queue_t gloabaQue = dispatch_get_global_queue(0, 0);
    dispatch_async(gloabaQue, ^{
        AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
        manager.responseSerializer = [AFHTTPResponseSerializer serializer];
        NSString *url = ServerIp@"/matchApp/matchDetail";
        NSDictionary *param = @{@"id":self.matchID};
        [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            
            NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
            NSDictionary *imagsDic = jsonDic[@"match"];
            NSArray *imagesArra = imagsDic[@"matchImgs"];
            for (NSDictionary *dict in imagesArra) {
                NSString *imagePath = dict[@"img"][@"path"];
                NSData *data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imagePath]];
                UIImage *image = [UIImage imageWithData:data];
                NSLog(@"w = %f,h = %f",image.size.width,image.size.height);
                CGFloat rowheight = (WIDTH * image.size.height) / image.size.width;
                NSString *rowheights = [NSString stringWithFormat:@"%f",rowheight];
                [self.imagesArray addObject:imagePath];
                [self.rowsArray addObject:rowheights];
            }
            dispatch_async(dispatch_get_main_queue(), ^{
                self.title = jsonDic[@"match"][@"name"];
                [self.tableView reloadData];

            });
            
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];

    });
}
-(UIView *)showView{
    if (_showView == nil) {
        _showView = [[UIView alloc] initWithFrame:CGRectMake(0, HEIGHT, WIDTH, scaleTopAndBottom(50))];
        [self.view addSubview:_showView];
        [self addBtnInFatherView:_showView];
    }
    return _showView;
}
-(void)addBtnInFatherView:(UIView *)cell{
    UIView *lineView = [[UIView alloc] init];
    lineView.backgroundColor = COLOR_HEX(0xE8E8E8);
    cell.backgroundColor = [UIColor whiteColor];
    [cell addSubview:lineView];
    [lineView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.left.right.equalTo(cell);
        make.height.mas_equalTo(0.5f);
    }];
    self.applyBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    self.applyBtn.backgroundColor = COLOR_HEX(0xF9D025);
    [self.applyBtn setTitle:@"立即报名" forState:UIControlStateNormal];
    self.applyBtn.layer.cornerRadius = 15;
    self.applyBtn.layer.masksToBounds = YES;
    [self.applyBtn addTarget:self action:@selector(GoReportpage:) forControlEvents:UIControlEventTouchUpInside];
    [cell addSubview:self.applyBtn];
    [self.applyBtn mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(cell.mas_bottom).offset(scaleTopAndBottom(-10));
        make.left.equalTo(cell.mas_left).offset(scaleLeftAndRight(100));
        make.right.equalTo(cell.mas_right).offset(scaleLeftAndRight(-100));
        make.top.equalTo(cell.mas_top).offset(scaleTopAndBottom(10));
    }];
}

-(void)GoReportpage:(UIButton *)btn{
    AFHTTPSessionManager *manager = [AFHTTPSessionManager manager];
    manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    NSString *url = ServerIp@"/matchApp/checkMatchCondition";
    NSString *sessionID = [[NSUserDefaults standardUserDefaults] objectForKey:@"sessionId"];
    if (!sessionID) {
        LoginUserViewController *loginVc = [[LoginUserViewController alloc] init];
        loginVc.chooseTypeId = @"1";
        [self.navigationController pushViewController:loginVc animated:YES];
        return;
    }
    NSDictionary *param = @{@"matchId":self.matchID,@"sessionId":sessionID};
    [manager POST:url parameters:param progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *jsonDic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        if ([jsonDic[@"result"] integerValue] == 0) {
            self.applyBtn.userInteractionEnabled = NO;
            self.applyBtn.backgroundColor = COLOR_HEX(0xadadad);
            [self.applyBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            NSLog(@"报名信息%@",jsonDic[@"msg"]);
            CommitDataViewController *vc = [[CommitDataViewController alloc] init];
            vc.matchStarttime = self.matchStarttime;
            vc.matchId = self.matchID;
            vc.themeTitle = self.title;
            [self.navigationController pushViewController:vc animated:YES];
        }else{

            UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:jsonDic[@"msg"] message:nil delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil, nil];
            [alertView show];
        }

        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
    

}
-(NSMutableArray *)imagesArray{
    if (_imagesArray == nil) {
        _imagesArray = [[NSMutableArray alloc] init];
    }
    return _imagesArray;
}
-(NSMutableArray *)rowsArray{
    if (_rowsArray == nil) {
        _rowsArray = [[NSMutableArray alloc] init];
    }
    return _rowsArray;
}
-(void)showShareUI{
    UIView *backView = [[UIView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    backView.alpha = 0.5f;
    backView.backgroundColor = [UIColor blackColor];
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(removebackView:)];
    [backView addGestureRecognizer:tap];
    [[UIApplication sharedApplication].keyWindow addSubview:backView];
    _shareView = [[QQAndWechatShareView alloc] initWithFrame:CGRectMake(0, HEIGHT, WIDTH, scaleTopAndBottom(94))];
    [_shareView.QQBtn addTarget:self action:@selector(QQShare:) forControlEvents:UIControlEventTouchUpInside];
    [_shareView.WechatBtn addTarget:self action:@selector(WechatShare:) forControlEvents:UIControlEventTouchUpInside];
    [[UIApplication sharedApplication].keyWindow addSubview:_shareView];
    [UIView animateWithDuration:0.1 animations:^{
        _shareView.frame = CGRectMake(0,HEIGHT - scaleTopAndBottom(94), WIDTH, scaleTopAndBottom(94));
    }];
}
-(void)WechatShare:(UIButton *)btn{
    /** 标题
     * @note 长度不能超过512字节
     */
    // @property (nonatomic, retain) NSString *title;
    /** 描述内容
     * @note 长度不能超过1K
     */
    //@property (nonatomic, retain) NSString *description;
    /** 缩略图数据
     * @note 大小不能超过32K
     */
    //  @property (nonatomic, retain) NSData   *thumbData;
    /**
     * @note 长度不能超过64字节
     */
    // @property (nonatomic, retain) NSString *mediaTagName;
    /**
     * 多媒体数据对象，可以为WXImageObject，WXMusicObject，WXVideoObject，WXWebpageObject等。
     */
    // @property (nonatomic, retain) id        mediaObject;
    
    /*! @brief 设置消息缩略图的方法
     *
     * @param image 缩略图
     * @note 大小不能超过32K
     */
    //- (void) setThumbImage:(UIImage *)image;
    //缩略图
    UIImage *image = [UIImage imageNamed:@"LOGO4"];
    WXMediaMessage *message = [WXMediaMessage message];
    message.title = @"拼才艺,发现自己,展现自我";
    message.description = @"加入趣味赛事,增长经验值,让孩子在参与中获得自信与快乐";
    //png图片压缩成data的方法，如果是jpg就要用 UIImageJPEGRepresentation
    message.thumbData = UIImagePNGRepresentation(image);
    [message setThumbImage:image];
    WXWebpageObject *ext = [WXWebpageObject object];
    ext.webpageUrl = [NSString stringWithFormat:ServerIp@"/h5/m_share?id=%@",self.matchID];
    message.mediaObject = ext;
    message.mediaTagName = @"ISOFTEN_TAG_JUMP_SHOWRANK";
    
    SendMessageToWXReq *sentMsg = [[SendMessageToWXReq alloc]init];
    sentMsg.message = message;
    sentMsg.bText = NO;
    sentMsg.scene =  WXSceneSession;
    //    //选择发送到会话(WXSceneSession)或者朋友圈(WXSceneTimeline)
    //    if (isPengyouquan) {
    //        sentMsg.scene = WXSceneTimeline;  //分享到朋友圈
    //    }else{
    //        sentMsg.scene =  WXSceneSession;  //分享到会话。
    //    }
    
    //如果我们想要监听是否成功分享，我们就要去appdelegate里面 找到他的回调方法
    // -(void) onResp:(BaseResp*)resp .我们可以自定义一个代理方法，然后把分享的结果返回回来。
    appdelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
    //添加对appdelgate的微信分享的代理
    //    appdelegate.wxDelegate = self;
    BOOL isSuccess = [WXApi sendReq:sentMsg];
}
-(void)QQShare:(UIButton *)btn{
    //创建分享消息对象
    UMSocialMessageObject *messageObject = [UMSocialMessageObject messageObject];
    
    //创建网页内容对象
    NSString* thumbURL =  @"http://www.tj698.com/resource/img/logo.png";
    UMShareWebpageObject *shareObject = [UMShareWebpageObject shareObjectWithTitle:@"拼才艺,发现自己,展现自我" descr:@"加入趣味赛事,增长经验值,让孩子在参与中获得自信与快乐" thumImage:thumbURL];
    //设置网页地址
    shareObject.webpageUrl = [NSString stringWithFormat:ServerIp@"/h5/m_share?id=%@",self.matchID];
    //分享消息对象设置分享内容对象
    messageObject.shareObject = shareObject;
    
    //调用分享接口
    [[UMSocialManager defaultManager] shareToPlatform:UMSocialPlatformType_QQ messageObject:messageObject currentViewController:self completion:^(id data, NSError *error) {
        if (error) {
            UMSocialLogInfo(@"************Share fail with error %@*********",error);
        }else{
            if ([data isKindOfClass:[UMSocialShareResponse class]]) {
                UMSocialShareResponse *resp = data;
                //分享结果消息
                UMSocialLogInfo(@"response message is %@",resp.message);
                //第三方原始返回的数据
                UMSocialLogInfo(@"response originalResponse data is %@",resp.originalResponse);
                
            }else{
                UMSocialLogInfo(@"response data is %@",data);
            }
        }
    }];
    
}
-(void)removebackView:(UITapGestureRecognizer *)tap{
    
    [UIView animateWithDuration:0.1 animations:^{
        UIView *view = tap.view;
        [view removeFromSuperview];
        [_shareView removeFromSuperview];
    }];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView{
    
    if (scrollView.contentOffset.y > _offsetY && scrollView.contentOffset.y > 0) {
//        向上滑动
        NSLog(@"赏花");
        [UIView animateWithDuration:0.1 animations:^{
            _showView.frame = CGRectMake(0,HEIGHT, WIDTH, scaleTopAndBottom(50));
        }];
        if (scrollView.contentOffset.y == scrollView.contentSize.height - self.tableView.frame.size.height - scaleTopAndBottom(50)) {
            self.tableView.bounces = NO;
            self.showView.frame = CGRectMake(0,HEIGHT - scaleTopAndBottom(50), WIDTH, scaleTopAndBottom(50));
        }
        
    }else{
//        向下滑动
        NSLog(@"下滑");
        [UIView animateWithDuration:0.1 animations:^{
            self.showView.frame = CGRectMake(0,HEIGHT - scaleTopAndBottom(50), WIDTH, scaleTopAndBottom(50));
        }];
    }
    _offsetY = scrollView.contentOffset.y;
    
}
-(void)tabBar:(UITabBar *)tabBar didSelectItem:(UITabBarItem *)item{
    
    item.imageInsets = UIEdgeInsetsMake(6, 0, -6, 0);
    self.navigationController.tabBarController.selectedIndex = 4;
    UITabBarItem *item2 = [self.tabBarController.tabBar.items objectAtIndex:1];
    item2.imageInsets = UIEdgeInsetsMake(0, 0, 0, 0);
    NSLog(@"这是点击了吗");
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
